package resource

import (
	"project-info/src/handle/common"
	"project-info/src/handle/response"
	"project-info/src/model"
	"gorm.io/gorm"

	"project-info/src/lib")

type K8sClusterReq struct {
	Query string `json:"query"`
	common.PageRequest
}

func AddK8sCluster(c *lib.GinContext) error {
	// 1.解析参数
	var k8sCluster *model.K8sCluster
	if err := c.Bind(&k8sCluster); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	// 2. 检验k8sCluster 是否存在
	var count int64
	db := model.DB().Model(&model.K8sCluster{}).Where("cluster = ?", k8sCluster.Cluster)
	if err := db.Count(&count).Error; err != nil {
		return response.JsonFail(c, "查询数据库失败")
	}
	if count > 0 && k8sCluster.Id == 0 {
		return response.JsonFail(c, "集群已存在")
	}

	// 3.保存数据
	if k8sCluster.Id == 0 {
		model.DB().Create(k8sCluster)
	} else {
		model.DB().Save(k8sCluster)
	}
	return response.JsonOk(c, k8sCluster, "success")
}

func PageK8sCluster(c *lib.GinContext) error {
	// 1.解析参数
	var req K8sClusterReq
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	// 2.查询数据
	var k8sClusters []*model.K8sCluster
	var total int64
	db := model.DB().Model(&model.K8sCluster{})
	if req.Query != "" {
		db = db.Where("cluster like ?", "%"+req.Query+"%")
	}
	if err := db.Count(&total).Order("id desc").Offset((req.Page - 1) * req.Size).Limit(req.Size).Find(&k8sClusters).Error; err != nil && err != gorm.ErrRecordNotFound {
		return response.JsonFail(c, "查询数据库失败")
	}

	// 3.返回数据
	return response.JsonOk(c, map[string]interface{}{"records": k8sClusters, "total": total}, "success")
}

func DeleteK8sCluster(c *lib.GinContext) error {
	// 1.解析参数
	var k8sCluster *model.K8sCluster
	if err := c.Bind(&k8sCluster); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	// 2.删除数据
	if err := model.DB().Delete(k8sCluster).Error; err != nil {
		return response.JsonFail(c, "删除数据库失败")
	}

	return response.JsonOk(c, nil, "删除成功")
}

func ListK8sCluster(c *lib.GinContext) error {
	var k8sClusters []*model.K8sCluster
	if err := model.DB().Find(&k8sClusters).Error; err != nil {
		return response.JsonFail(c, "查询数据库失败")
	}
	var options []*common.OptionRes
	for _, k8sCluster := range k8sClusters {
		options = append(options, &common.OptionRes{
			Value: k8sCluster.Cluster,
			Label: k8sCluster.Cluster,
		})
	}
	return response.JsonOk(c, options, "success")
}
